package cmd

import (
	"fmt"
	"im-tools/internal/config"
	"im-tools/internal/model"
	"im-tools/pkg"
	"net/http"
	"time"

	"github.com/duke-git/lancet/netutil"
	"github.com/goccy/go-json"
	"github.com/gookit/color"
	"github.com/spf13/cobra"
)

var userCreateCmd = &cobra.Command{
	Use:   "createUser",
	Short: "创建用户",
	Long:  `批量创建用户`,
	Run: func(cmd *cobra.Command, args []string) {
		var userCount int
		for {
			color.Info.Println("输入新用户的数量[1-999]:")
			if _, err := fmt.Scanln(&userCount); err != nil {
				continue
			}

			if userCount > 0 {
				break
			} else if userCount >= 1000 {
				color.Error.Println("每次创建的用户数应该小于1000")
				continue
			}
		}

		for i := 0; i < userCount; i++ {
			login(pkg.GenPhone())
			time.Sleep(1 * time.Second)
		}

	},
}

func login(loginAccount string) {
	request := &netutil.HttpRequest{
		RawURL: config.API + "/api/zkim/sys/userLogin",
		Method: "POST",
	}

	loginReq := &model.LoginReq{
		DeviceType:    "ANDROID",
		LoginAccount:  loginAccount,
		LoginPassword: "",
		LoginType:     2,
	}

	postData, err := json.Marshal(loginReq)
	if err != nil {
		fmt.Println(err)
	}
	request.Body = postData

	headers := http.Header{}
	headers.Add("Content-Type", "application/json")
	request.Headers = headers

	httpClient := netutil.NewHttpClient()
	resp, err := httpClient.SendRequest(request)
	if err != nil || resp.StatusCode != 200 {
		fmt.Println(resp.StatusCode)
		return
	}
	color.Info.Printf("成功创建用户: %v\n", loginAccount)
}

func init() {
	rootCmd.AddCommand(userCreateCmd)
}
